package thread;

import sun.nio.ch.ThreadPool;

import javax.swing.plaf.IconUIResource;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Miyako
 * @Date: 2024-07-23-16:58
 * @Description: 线程池属性
 */
public class ThreadPoolDemo02 {
    private static int taskCount = 0;//任务计数器
    private static int corePoolSize=2;//核心线程数
    private static int maximumPoolSize=3;//最大线程数
    private static long keepAliveTime=1;//线程空闲时间
    private static TimeUnit unit = TimeUnit.SECONDS;//时间单位
    //任务队列
    private static LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1);//最多容纳1个任务
    //线程工厂
    private static ThreadFactory threadFactory = new ThreadFactory() {
        public Thread newThread(Runnable r) {
            return new Thread(r, "MyThread-" + (++taskCount));//创建线程
        }
    };
    //拒绝策略,默认策略。如果线程和队列都满了，就直接抛出异常
    private  static ThreadPoolExecutor.AbortPolicy handler =
            new ThreadPoolExecutor.AbortPolicy();


    public static void main(String[] args) {

        //创建一个线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,//核心线程数
                maximumPoolSize,//最大线程数
                keepAliveTime,//线程空闲时间
                unit,//时间单位，秒
                workQueue,//任务队列
                threadFactory,//线程工厂
                handler//拒绝策略
        );
        executor.execute(()-> {//启动线程0执行
            System.out.println(Thread.currentThread().getName()+":task1");
            try{Thread.sleep(1000);}catch (InterruptedException e){}
        });
        executor.execute(()-> {//启动新线程执行
            System.out.println(Thread.currentThread().getName()+":task2");
            try{Thread.sleep(1000);}catch (InterruptedException e){}
        });
        executor.execute(()-> {//放入队列,等待线程执行
            System.out.println(Thread.currentThread().getName()+":task3");
            try{Thread.sleep(1000);}catch (InterruptedException e){}
        });
        executor.execute(()-> {//队列满了，再启动新线程
            System.out.println(Thread.currentThread().getName()+":task4");
            try{Thread.sleep(1000);}catch (InterruptedException e){}
        });
//        executor.execute(()-> {//线程池满了，队列满了,拒绝策略抛出异常
//            System.out.println(Thread.currentThread().getName()+":task5");
//            try{Thread.sleep(1000);}catch (InterruptedException e){}
//        });

        executor.shutdown();
//        executor.shutdownNow();



    }
}
